package org.xlp.bean.impl;

import org.xlp.assertion.AssertUtils;
import org.xlp.bean.annotation.Component;
import org.xlp.bean.base.IBeanDefinition;
import org.xlp.bean.base.IBeanDefinitionCreator;
import org.xlp.bean.exception.BeanBaseException;
import org.xlp.utils.ClassLoaderUtils;

/**
 * {@link org.xlp.bean.annotation.Component}注解标识的类 Bean定义创建器
 */
public class ComponentAnnotationBeanDefinitionCreator implements IBeanDefinitionCreator {
    /**
     * 根据给定的bean创建对应的bean定义
     *
     * @param beanClass bean类型
     * @return bean定义对象
     */
    @Override
    public IBeanDefinition createBeanDefinition(Class<?> beanClass) {
        return new ComponentAnnotationBeanDefinition(beanClass);
    }

    /**
     * 根据给定的bean类型名称创建对应的bean定义
     *
     * @param beanClassName bean类型名称
     * @param classLoader   类加载器
     * @return
     * @throws NullPointerException 假如第一个参数为null，则抛出该异常
     * @throws BeanBaseException    假如创建失败，则抛出该异常
     */
    @Override
    public IBeanDefinition createBeanDefinition(String beanClassName, ClassLoader classLoader) {
        AssertUtils.isNotNull(beanClassName, "beanClassName parameter must not be null!");
        classLoader = classLoader == null ? ClassLoaderUtils.getDefaultClassLoader() : classLoader;
        try {
            Class<?> beanClass = Class.forName(beanClassName, true, classLoader);
            if (beanClass.getAnnotation(Component.class) == null){
                throw new BeanBaseException(beanClass + "该类缺少" + Component.class.getName() + "注解");
            }
            return createBeanDefinition(beanClass);
        } catch (ClassNotFoundException e) {
            throw new BeanBaseException(e);
        }
    }
}
